package com.sikaryofficial.workbench.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sikaryofficial.system.api.model.att.AttachmentResp;
import com.sikaryofficial.workbench.domain.entity.Attachment;
import com.sikaryofficial.workbench.domain.mapping.AttachmentMapping;
import com.sikaryofficial.workbench.mapper.AttachmentMapper;
import com.sikaryofficial.workbench.service.IAttachmentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 附件Service业务层处理
 *
 * @author wuweihong
 * @date 2024-09-23
 */
@Service
@Slf4j
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements IAttachmentService {
    /**
     * 保持附件 ：图片
     *
     * @param objectId
     * @param attachmentRespList
     * @param userId
     */
    @Override
    public void saveAttachmentList(Long objectId, List<AttachmentResp> attachmentRespList, Long userId) {
        if (CollUtil.isEmpty(attachmentRespList)) {
            return;
        }
        List<Attachment> attachments = Lists.newArrayList();
        for (AttachmentResp attendReq : attachmentRespList) {
            Attachment attachment = Attachment.builder()
                    .attachmentId(IdWorker.getId())
                    .objectId(objectId)
                    .description(attendReq.getDescription())
                    .url(attendReq.getUrl())
                    .hasCover(attendReq.getHasCover())
                    .height(attendReq.getHeight())
                    .width(attendReq.getWidth())
                    .duration(attendReq.getDuration())
                    .hasMedia(attendReq.getHasMedia())
                    .createdBy(userId)
                    .createdTime(new Date())
                    .build();
            attachments.add(attachment);
        }
        this.saveBatch(attachments);
    }

    /**
     * 删除附件 ：图片
     *
     * @param objectId
     * @param userId
     */
    @Override
    public boolean deleteAttachmentList(Long objectId, Long userId) {
        List<Attachment> list = this.list(new LambdaQueryWrapper<Attachment>()
                .eq(Attachment::getObjectId, objectId)
                .eq(Attachment::getDeletedVersion, 0L)
        );
        List<Attachment> attachments = Lists.newArrayList();
        for (Attachment attendReq : list) {
            Attachment attachment = Attachment.builder()
                    .deletedVersion(attendReq.getAttachmentId())
                    .updatedBy(userId)
                    .updatedTime(new Date())
                    .attachmentId(attendReq.getAttachmentId())
                    .objectId(attendReq.getObjectId())
                    .build();
            attachments.add(attachment);
            log.info("删除附件，附件ID：" + attendReq.getAttachmentId());
        }
        return this.saveOrUpdateBatch(attachments);
    }

    /**
     * 根据对象ID获取附件 ：图片
     *
     * @param objectId
     */
    @Override
    public List<AttachmentResp> getAttachmentById(Long objectId) {
        if (Objects.isNull(objectId)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<Attachment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(Attachment::getAttachmentId, Attachment::getUrl, Attachment::getHasCover, Attachment::getObjectId
                        , Attachment::getHeight, Attachment::getWidth, Attachment::getDuration, Attachment::getHasMedia)
                .eq(Attachment::getObjectId, objectId)
                .eq(Attachment::getDeletedVersion, 0L);
        List<Attachment> attachments = this.list(queryWrapper);
        if (Objects.isNull(attachments)) {
            return Collections.emptyList();
        }
        // 按照主键ID顺序 ASC排序
        attachments.sort(Comparator.comparing(Attachment::getAttachmentId));
        return AttachmentMapping.INSTANCE.coverListToResp(attachments);
    }

    /**
     * 根据对象ID获取附件 ：图片及图片描述
     *
     * @param objectId
     * @return
     */
    @Override
    public List<AttachmentResp> getAttachmentDescById(Long objectId) {
        if (Objects.isNull(objectId)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<Attachment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(Attachment::getAttachmentId, Attachment::getUrl, Attachment::getHasCover, Attachment::getObjectId
                        , Attachment::getDescription, Attachment::getHeight, Attachment::getWidth, Attachment::getDuration, Attachment::getHasMedia)
                .eq(Attachment::getObjectId, objectId)
                .eq(Attachment::getDeletedVersion, 0L);
        List<Attachment> attachments = this.list(queryWrapper);
        if (Objects.isNull(attachments)) {
            return Collections.emptyList();
        }
        // 按照主键ID顺序 ASC排序
        attachments.sort(Comparator.comparing(Attachment::getAttachmentId));
        return AttachmentMapping.INSTANCE.coverListToResp(attachments);
    }

    /**
     * 根据对象ID集合获取附件 ：图片
     *
     * @param objectIds
     */
    @Override
    public Map<Long, List<AttachmentResp>> getAttachmentByIds(List<Long> objectIds) {
        if (CollUtil.isEmpty(objectIds)) {
            return new HashMap<>(0);
        }
        LambdaQueryWrapper<Attachment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(Attachment::getAttachmentId, Attachment::getUrl, Attachment::getHasCover, Attachment::getObjectId
                        , Attachment::getDescription, Attachment::getHeight, Attachment::getWidth, Attachment::getDuration, Attachment::getHasMedia)
                .in(Attachment::getObjectId, objectIds)
                .eq(Attachment::getDeletedVersion, 0L);
        List<Attachment> attachments = this.list(queryWrapper);
        if (CollUtil.isEmpty(attachments)) {
            return new HashMap<>(0);
        }
        List<AttachmentResp> attachmentRests = AttachmentMapping.INSTANCE.coverListToResp(attachments);
        // 按照主键ID顺序 ASC排序
        attachmentRests.sort(Comparator.comparing(AttachmentResp::getAttachmentId));
        return attachmentRests.stream().collect(Collectors.groupingBy(AttachmentResp::getObjectId));
    }
}
